home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9310 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  68 lines

  1. Path: hubcap.clemson.edu!hubcap!mjs
  2. From: mjs@hubcap.clemson.edu (M. J. Saltzman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Convert a float to an int ( and round up/down ? )
  5. Date: 7 Mar 96 16:21:03 GMT
  6. Organization: Clemson University
  7. Message-ID: <mjs.826215663@hubcap>
  8. References: <826162763.17141@farlight.demon.co.uk>
  9. NNTP-Posting-Host: hubcap.clemson.edu
  10. X-Newsreader: NN version 6.5.0 #1
  11.  
  12. j shipley <jonathan@farlight.demon.co.uk> writes:
  13.  
  14. >I am trying to convert a variable of type float to an int.
  15.  
  16. You need to be more specific about what you mean here.  (See below.)
  17.  
  18. >How can this be done?
  19.  
  20. >I have tried     (int) variable
  21. >i.e what I thought a cast was, but it does not work.
  22.  
  23. A cast converts the *value* of a variable (or expression) to a new
  24. type, changing the representation if necessary (the float-to-int cast
  25. throws away the fractional part of the float and converts what's left
  26. to an int).  It does not reinterpret the bits stored in the variable.
  27. If reinterpreting the bits is your goal, you might be able to use a
  28. union or something like
  29.  
  30.     float x = 1.0;
  31.     int  i = *(int *) &x;
  32.  
  33. in your compiler, but the result is not portable (in fact it's
  34. undefined).  Better would be to redesign your program so that you
  35. don't need to do this.
  36.  
  37. >Part 2:
  38.  
  39. >Can I round a float up/down to the nearest number?
  40.  
  41.     #define ROUND(x) ((int) ((x) >= 0.0 ? (x) + 0.5 : (x) - 0.5)
  42.  
  43. If you want anything other than rounding away from zero when the fractional
  44. part is exactly 0.5, then you have to write something more sophisticated.
  45.  
  46. >Does a cast do the same as using the modulus operator, %? (in this case).
  47.  
  48. No.  A cast from float to int discards the fractional part (truncating
  49. toward zero).  The modulus operator produces the integer remainder
  50. after an integer division, e.g. 14 / 3 == 4, 14 % 3 == 2.  (A
  51. floating-point version is provided by the math.h function fmod().)  If
  52. you want the fractional part of a float, #include <math.h> and use the
  53. modf() function, or use 
  54.  
  55.     float frac = x - (int) x;
  56.  
  57. if you are sure that the integer part of x will fit in an int.
  58.  
  59. >I am using Borland C 3.1, and A Book On C (Kelly/Pohl) - neither of which 
  60. >has informed me.
  61.  
  62. >Thanks for your help.
  63.  
  64. -- 
  65.         Matthew Saltzman
  66.         Clemson University Math Sciences
  67.         mjs@clemson.edu
  68.